import axios from 'axios'
import { getConcurrency } from '@/config/batchProcessing'
import { API_CONFIG, getApiUrl, getStatusUrl, getDownloadUrl } from '@/config/api'
import { sessionManager } from '../utils/sessionManager'

// 创建 axios 实例
const api = axios.create({
    baseURL: API_CONFIG.BASE_URL,
    timeout: API_CONFIG.TIMEOUT, // 5分钟超时 (图片处理可能需要更长时间)
    headers: {
        'Content-Type': 'application/json'  // 默认JSON，上传时会自动覆盖为multipart/form-data
    }
})

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        // 添加会话ID到请求头
        const sessionId = sessionManager.getSessionId()
        if (sessionId) {
            config.headers['X-Session-ID'] = sessionId
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        console.error('API Error:', error)
        return Promise.reject(error)
    }
)

// 图片增强 API - 使用预签名URL流程（新流程）
export const enhanceImageAPI = async (imageDataUrl: string) => {
    console.log('开始调用API...')

    // 将 base64 转换为 blob
    const response = await fetch(imageDataUrl)
    const blob = await response.blob()
    console.log('图片转换完成，大小:', blob.size)

    try {
        // 1. 获取预签名URL
        console.log('🚀 ========== 步骤1: 调用获取预签名URL接口 ===========')
        console.log('📍 接口地址: /api/v1/upload/presigned-url')
        const sessionId = sessionManager.getSessionId()
        const user_id = sessionId || 'anonymous'
        console.log('👤 用户ID:', user_id)

        const presignedResponse = await api.post('/api/v1/upload/presigned-url', {
            user_id: user_id,
            file_type: blob.type || 'image/jpeg',
            file_size: blob.size,
            filename: 'image.jpg'
        })

        console.log('✅ 预签名URL接口调用成功！')
        console.log('📦 完整响应数据:', presignedResponse.data)
        
        if (!presignedResponse.data.success) {
            console.error('❌ 获取预签名URL失败:', presignedResponse.data.error)
            throw new Error(`获取预签名URL失败: ${presignedResponse.data.error}`)
        }

        const { presigned_url, cos_key } = presignedResponse.data
        
        // ⚠️ 关键检查：cos_key是否存在
        console.log('===========================================================')
        console.log('🔍 关键检查: cos_key 是否存在？')
        console.log('  cos_key 值:', cos_key)
        console.log('  cos_key 类型:', typeof cos_key)
        console.log('  cos_key 是否为空:', !cos_key ? '是（❌）' : '否（✅）')
        console.log('  presigned_url 值:', presigned_url)
        console.log('===========================================================')

        if (!cos_key) {
            console.error('❌ 致命错误: cos_key 为空或undefined！')
            console.error('  这将导致后续步骤失败')
            console.error('  完整响应数据:', presignedResponse.data)
            throw new Error('cos_key为空，无法继续处理')
        }

        // 📁 用户上传的原始图片信息
        console.log(' ')
        console.log('📁 用户上传的原始图片信息:')
        console.log('  🔑 COS文件键(cos_key):', cos_key)
        console.log('  📂 存储路径: uploads/', user_id, '/目录')
        console.log('  📏 图片大小:', blob.size, ' bytes')
        console.log('  📄 图片类型:', blob.type)

        // 🌐 上传到COS桶的图片URL (处理前)
        const cosInternalUrl = `https://photoenhancei-bj-1259206939.cos-internal.ap-beijing.myqcloud.com/${cos_key}`
        const cosPublicUrl = `https://cdn.gongjuxiang.work/${cos_key}`
        console.log(' ')
        console.log('🌐 上传到COS桶的图片URL (处理前):')
        console.log('  🔗 COS内网URL:', cosInternalUrl)
        console.log('  🌍 CDN公网URL:', cosPublicUrl)
        console.log('  📤 预签名URL:', presigned_url)
        console.log('===========================================================')
        console.log(' ')

        // 2. 直接上传到COS
        console.log('🚀 ========== 步骤2: 上传图片到COS ===========')
        console.log('📤 上传地址:', presigned_url)
        console.log('📦 上传数据大小:', blob.size, ' bytes')
        
        const uploadResponse = await fetch(presigned_url, {
            method: 'PUT',
            body: blob,
            headers: {
                'Content-Type': blob.type || 'image/jpeg',
                'x-cos-acl': 'public-read'
            }
        })

        if (!uploadResponse.ok) {
            console.error('❌ 上传到COS失败')
            console.error('  HTTP状态:', uploadResponse.status)
            console.error('  状态文本:', uploadResponse.statusText)
            throw new Error(`上传到COS失败: ${uploadResponse.status}`)
        }
        console.log('✅ 上传到COS成功！')
        console.log('  HTTP状态:', uploadResponse.status)
        console.log(' ')

        // 3. 通知处理图片
        console.log('🚀 ========== 步骤3: 通知后端处理图片 ===========')
        console.log('📍 接口地址: /api/v1/single-process-uploaded-image')
        console.log('📦 请求参数:')
        console.log('  {')
        console.log('    cos_key: "' + cos_key + '",')
        console.log('    tile_size: 400,')
        console.log('    quality_level: "high",')
        console.log('    user_id: "' + user_id + '"')
        console.log('  }')
        console.log(' ')
        console.log('⚠️ 确认: cos_key值为:', cos_key)
        
        const enhanceResponse: any = await api.post('/api/v1/single-process-uploaded-image', {
            cos_key: cos_key,
            tile_size: 400,
            quality_level: 'high',
            user_id: user_id
        })

        console.log('✅ 后端处理接口调用成功！')
        console.log('📦 响应数据:', enhanceResponse.data)

        if (enhanceResponse.data.success) {
            // 🖼️ GPU服务器返回的处理后图片URL
            console.log('===========================================================')
            console.log('✅ GPU服务器处理完成 - 返回结果')
            console.log('🖼️ GPU服务器返回的处理后图片URL:')
            console.log('  🚀 结果CDN URL:', enhanceResponse.data.cdn_url)
            console.log('  📂 存储路径: processed/目录')
            console.log(' ')
            console.log('📊 处理性能统计:')
            console.log('  🆔 任务ID:', enhanceResponse.data.task_id)
            console.log('  ⏱️ 下载时间:', enhanceResponse.data.download_time || 0, 's')
            console.log('  🔧 处理时间:', enhanceResponse.data.processing_time || 0, 's')
            console.log('  ⬆️ 上传时间:', enhanceResponse.data.upload_time || 0, 's')
            console.log('  🕐 总时间:', enhanceResponse.data.total_time || 0, 's')
            console.log(' ')
            console.log('🔄 流程总结:')
            console.log('  1️⃣ 用户上传 → COS桶 (uploads/目录)')
            console.log('  2️⃣ GPU处理 → 增强图片')
            console.log('  3️⃣ 结果上传 → COS桶 (processed/目录)')
            console.log('  4️⃣ 返回URL → 前端显示')
            console.log('===========================================================')

            return {
                data: {
                    cdn_url: enhanceResponse.data.cdn_url,
                    task_id: enhanceResponse.data.task_id
                }
            }
        } else {
            throw new Error(`图片处理失败: ${enhanceResponse.data.error}`)
        }

    } catch (error: any) {
        console.error('===========================================================')
        console.error('❌ 处理失败详情:')
        console.error('  错误类型:', error.name)
        console.error('  错误消息:', error.message)
        console.error('  HTTP状态:', error.response?.status)
        console.error('  响应数据:', error.response?.data)
        console.error('  请求配置:', error.config?.url)
        console.error('===========================================================')
        throw error
    }
}
// 旧流程已移除，现在只使用预签名URL直接上传流程

// 图片增强 API - 仅提交任务（用于流水线处理）
export const submitImageTask = async (imageDataUrl: string) => {
    console.log('提交图片处理任务...')

    // 将 base64 转换为 blob
    const response = await fetch(imageDataUrl)
    const blob = await response.blob()
    console.log('图片转换完成，大小:', blob.size)

    // 创建 FormData
    const formData = new FormData()
    formData.append('file', blob, 'image.jpg')
    formData.append('tile_size', '400')
    formData.append('quality_level', 'high')

    // 添加会话ID
    const sessionId = sessionManager.getSessionId()
    if (sessionId) {
        formData.append('session_id', sessionId)
    }

    console.log('发送请求到:', getApiUrl(API_CONFIG.ENDPOINTS.ENHANCE))

    // 发送请求到真实的API接口
    const apiResponse = await api.post(API_CONFIG.ENDPOINTS.ENHANCE, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        timeout: API_CONFIG.TIMEOUT, // 5分钟超时
        onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
            console.log(`上传进度: ${percentCompleted}%`);
        }
    })

    console.log('任务提交响应:', apiResponse.data)

    // 检查是否是异步任务响应
    if (apiResponse.data.task_id && apiResponse.data.status) {
        console.log('任务已提交，任务ID:', apiResponse.data.task_id)

        // 添加任务到会话管理器
        sessionManager.addPendingTask(apiResponse.data.task_id)

        return {
            taskId: apiResponse.data.task_id,
            status: apiResponse.data.status
        }
    }

    return apiResponse
}

// 模拟 API（用于开发测试）
export const mockEnhanceImageAPI = async (imageDataUrl: string): Promise<{ data: { enhanced_image: string } }> => {
    // 模拟处理时间
    await new Promise(resolve => setTimeout(resolve, 3000))

    // 返回模拟的增强图片（实际上是原图，但可以用于测试界面）
    return {
        data: {
            enhanced_image: imageDataUrl
        }
    }
}

// 轮询任务结果
export const pollTaskResult = async (taskId: string, maxAttempts = API_CONFIG.POLLING.MAX_ATTEMPTS, interval = API_CONFIG.POLLING.INTERVAL): Promise<any> => {
    console.log(`开始轮询任务 ${taskId}...`)

    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
            console.log(`第 ${attempt} 次查询任务状态...`)

            // 查询任务状态 - 根据示例代码使用正确的路径
            const response = await api.get(getStatusUrl(taskId))
            console.log('任务状态响应:', response.data)

            // 显示进度信息
            if (response.data.progress) {
                console.log(`状态: ${response.data.status} (${(response.data.progress * 100).toFixed(1)}%)`)
            }

            if (response.data.status === 'completed') {
                console.log('任务完成！')

                // 从会话管理器中移除已完成的任务
                sessionManager.removePendingTask(taskId)

                // 获取下载链接
                const downloadUrl = getDownloadUrl(taskId)
                console.log('下载链接:', downloadUrl)

                // 返回包含下载链接的响应
                return {
                    data: {
                        download_url: downloadUrl,
                        enhanced_image: downloadUrl
                    }
                }
            } else if (response.data.status === 'failed') {
                // 从会话管理器中移除失败的任务
                sessionManager.removePendingTask(taskId)

                throw new Error(`任务失败: ${response.data.error || '未知错误'}`)
            } else if (response.data.status === 'processing' || response.data.status === 'queued') {
                console.log(`任务状态: ${response.data.status}，继续等待...`)
                // 等待指定时间后继续轮询
                await new Promise(resolve => setTimeout(resolve, interval))
            } else {
                console.log(`未知任务状态: ${response.data.status}`)
                await new Promise(resolve => setTimeout(resolve, interval))
            }

        } catch (error: any) {
            console.error(`轮询任务状态时出错:`, error)
            if (attempt === maxAttempts) {
                throw new Error(`任务轮询失败: ${error.message}`)
            }
            await new Promise(resolve => setTimeout(resolve, interval))
        }
    }

    throw new Error('任务处理超时，请稍后查看结果')
}

// 批量图片增强 API - 流水线式并发处理
export const batchEnhanceImagesAPI = async (imageDataUrls: string[]) => {
    console.log(`开始流水线式批量处理 ${imageDataUrls.length} 张图片...`)

    // 从配置文件获取并发数
    const { getScenario4Concurrency } = await import('../config/concurrencyConfig')
    const concurrency = await getScenario4Concurrency() // 场景4：多GPU+多图处理，动态并发数

    console.log(`🚀 流水线式并发处理，并发数: ${concurrency}`)

    // 使用流水线式并发处理
    return await processImagesWithPipelineAPI(imageDataUrls, concurrency)
}

// 流水线式并发处理函数
const processImagesWithPipelineAPI = async (imageDataUrls: string[], concurrency: number) => {
    const results: any[] = []
    const runningTasks: Promise<any>[] = []
    let currentIndex = 0

    // 启动初始的并发任务
    for (let i = 0; i < Math.min(concurrency, imageDataUrls.length); i++) {
        const promise = processImageWithPipelineAPI(imageDataUrls[currentIndex], currentIndex)
        runningTasks.push(promise)
        currentIndex++
    }

    // 当有任务完成时，启动新任务
    while (currentIndex < imageDataUrls.length || runningTasks.length > 0) {
        // 等待任意一个任务完成
        const completedTask = await Promise.race(runningTasks)
        results.push(completedTask)

        // 移除已完成的任务
        const completedIndex = runningTasks.findIndex(task => task === completedTask)
        if (completedIndex !== -1) {
            runningTasks.splice(completedIndex, 1)
        }

        // 启动新任务
        if (currentIndex < imageDataUrls.length) {
            const promise = processImageWithPipelineAPI(imageDataUrls[currentIndex], currentIndex)
            runningTasks.push(promise)
            currentIndex++
        }
    }

    console.log('🎉 流水线式批量处理完成，结果:', results)
    return results
}

// 带流水线的单张图片处理
const processImageWithPipelineAPI = async (imageDataUrl: string, index: number) => {
    try {
        console.log(`处理第 ${index + 1} 张图片...`)
        const result = await enhanceImageAPI(imageDataUrl)
        return {
            success: true,
            data: result.data,
            index: index
        }
    } catch (error: any) {
        console.error(`第 ${index + 1} 张图片处理失败:`, error)
        return {
            success: false,
            error: error.message || '处理失败',
            index: index
        }
    }
}

// 批量轮询任务结果
export const batchPollTaskResults = async (taskIds: string[], maxAttempts = API_CONFIG.POLLING.MAX_ATTEMPTS, interval = API_CONFIG.POLLING.INTERVAL) => {
    console.log(`开始批量轮询 ${taskIds.length} 个任务...`)

    const results = []

    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        console.log(`第 ${attempt} 次批量查询任务状态...`)

        const promises = taskIds.map(async (taskId, index) => {
            try {
                const response = await api.get(getStatusUrl(taskId))
                return {
                    taskId,
                    index,
                    status: response.data.status,
                    progress: response.data.progress,
                    error: response.data.error,
                    data: response.data
                }
            } catch (error: any) {
                return {
                    taskId,
                    index,
                    status: 'error',
                    error: error.message,
                    data: null
                }
            }
        })

        const responses = await Promise.all(promises)

        // 检查是否所有任务都完成
        const allCompleted = responses.every(r =>
            r.status === 'completed' || r.status === 'failed' || r.status === 'error'
        )

        if (allCompleted) {
            console.log('所有任务已完成')
            return responses.map(r => ({
                taskId: r.taskId,
                index: r.index,
                status: r.status,
                downloadUrl: r.status === 'completed'
                    ? getDownloadUrl(r.taskId)
                    : null,
                error: r.error
            }))
        }

        // 等待指定时间后继续轮询
        await new Promise(resolve => setTimeout(resolve, interval))
    }

    throw new Error('批量任务处理超时')
}

// 导出会话管理器，供组件使用
export { sessionManager }

// 手动取消会话任务的函数
export const cancelSessionTasks = async (): Promise<boolean> => {
    await sessionManager.cancelSessionTasks()
    return true
}

// 重置会话的函数
export const resetSession = (): void => {
    sessionManager.resetSession()
}

// 批量上传图片到COS
export const batchUploadToCOS = async (imageDataUrls: string[]) => {
    console.log(`[批量上传] 开始上传 ${imageDataUrls.length} 张图片到COS...`)
    
    const uploadResults = []
    const sessionId = sessionManager.getSessionId()
    const user_id = sessionId || 'anonymous'
    
    for (let i = 0; i < imageDataUrls.length; i++) {
        try {
            const imageDataUrl = imageDataUrls[i]
            
            // 将 base64 转换为 blob
            const response = await fetch(imageDataUrl)
            const blob = await response.blob()
            
            // 1. 获取预签名URL
            const presignedResponse = await api.post('/api/v1/upload/presigned-url', {
                user_id: user_id,
                file_type: blob.type || 'image/jpeg',
                file_size: blob.size,
                filename: `image_${i + 1}.jpg`
            })
            
            if (!presignedResponse.data.success) {
                throw new Error(`获取预签名URL失败: ${presignedResponse.data.error}`)
            }
            
            const { presigned_url, cos_key } = presignedResponse.data
            
            // 2. 上传到COS
            const uploadResponse = await fetch(presigned_url, {
                method: 'PUT',
                body: blob,
                headers: {
                    'Content-Type': blob.type || 'image/jpeg',
                    'x-cos-acl': 'public-read'
                }
            })
            
            if (!uploadResponse.ok) {
                throw new Error(`上传到COS失败: ${uploadResponse.status}`)
            }
            
            console.log(`[批量上传] 图片 ${i + 1}/${imageDataUrls.length} 上传成功: ${cos_key}`)
            
            uploadResults.push({
                index: i,
                success: true,
                cos_key: cos_key
            })
            
        } catch (error: any) {
            console.error(`[批量上传] 图片 ${i + 1} 上传失败:`, error)
            uploadResults.push({
                index: i,
                success: false,
                error: error.message
            })
        }
    }
    
    return uploadResults
}

// 批量处理已上传图片API（流式响应）
export const batchProcessUploadedImages = async (
    fileKeys: Array<{cos_key: string, quality_level?: string}>,
    onProgress?: (result: any) => void
) => {
    console.log(`[批量处理] 开始处理 ${fileKeys.length} 张图片...`)
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/api/v1/batch-process-uploaded-image`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Session-ID': sessionManager.getSessionId() || ''
        },
        body: JSON.stringify({
            images: fileKeys
        })
    })
    
    if (!response.ok) {
        throw new Error(`批量处理请求失败: ${response.status}`)
    }
    
    if (!response.body) {
        throw new Error('响应体为空')
    }
    
    // 流式读取响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    
    let buffer = ''
    const results: any[] = []
    
    while (true) {
        const {done, value} = await reader.read()
        
        if (done) {
            console.log('[批量处理] 流式响应接收完成')
            break
        }
        
        // 解码数据
        buffer += decoder.decode(value, {stream: true})
        
        // 按行分割（JSON Lines格式）
        const lines = buffer.split('\n')
        
        // 保留最后一个不完整的行
        buffer = lines.pop() || ''
        
        // 处理每一行
        for (const line of lines) {
            if (line.trim()) {
                try {
                    const result = JSON.parse(line)
                    results.push(result)
                    
                    // 调用进度回调
                    if (onProgress && !result.summary) {
                        onProgress(result)
                    }
                    
                    // 如果是汇总信息，记录日志
                    if (result.summary) {
                        console.log('[批量处理] 完成汇总:', result.summary)
                    } else {
                        console.log(`[批量处理] 图片 ${result.index + 1} 处理${result.success ? '成功' : '失败'}`)
                    }
                } catch (e) {
                    console.error('[批量处理] JSON解析失败:', line, e)
                }
            }
        }
    }
    
    return results
}

export default api
